package study.alibaba.sentinel.support.rule;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.apollo.ApolloDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
//@Configuration
public class ApolloRuleConfig {

    private String namespaceName = "";
    private String ruleKey = "";
    private String defaultRuleValue = "";

    @PostConstruct
    public void loadRules() {
        //
        ReadableDataSource<String, List<FlowRule>> dataSource = new ApolloDataSource<>(namespaceName,
                ruleKey,
                defaultRuleValue,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                }));
        //
        FlowRuleManager.register2Property(dataSource.getProperty());
    }
}
